package com.app.newcsc.fragment.main;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.app.AppApplication;
import com.app.newcsc.app.AppViewModelFactory;
import com.app.newcsc.databinding.FragmentTabMarketBinding;
import com.app.newcsc.entity.ConfigEntity;
import com.app.newcsc.entity.FiveBuyFiveSellEntity;
import com.app.newcsc.entity.GetTokenEntity;
import com.app.newcsc.entity.PayAccountEntity;
import com.app.newcsc.entity.PlanIndexEntity;
import com.app.newcsc.entity.WalletEntity;
import com.app.newcsc.fragment.my.exchangepoints.ExchangePointsFragment;
import com.app.newcsc.fragment.my.safe.SafeFragment;
import com.app.newcsc.utils.NumberUtils;
import com.app.newcsc.utils.ShareUtil;
import com.app.newcsc.utils.SpUtils;
import com.app.newcsc.utils.TextUtil;
import com.app.newcsc.utils.TimeUtil;
import com.app.newcsc.utils.ToastUtil;
import com.app.newcsc.utils.Utils;
import com.app.newcsc.view.AuthorizationDialog;
import com.app.newcsc.view.CustomPopWindow;
import com.app.newcsc.view.MCheckBox;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;

/**
 * 市场
 *
 * @author: woking
 * @date: 2021/6/7
 * @description：
 */
public class MarketFragment extends BaseFragment<FragmentTabMarketBinding, FundViewModel> {

    private boolean isBuy = true;
    private WalletEntity mCSCWalletEntity = null;
    private int buy_max_num = 500;
    private int sell_max_num = 500;
    private String cankaojiage_buy = "";
    private String cankaojiage_sell = "";
    private int  mAuthentication = -1;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_tab_market;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public FundViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(FundViewModel.class);
    }

    private int buy_index = 0;
    private int sell_index = 0;

    private void reFreshBuy() {
        List<FiveBuyFiveSellEntity> list = viewModel.mFiveBuyEntitys.getValue();
        if (null != list && list.size() > 0) {
            if (buy_index * 5 < list.size()) {
//                Log.e("TAG",buy_index+"====buy_index=======reFreshBuy===========");
                binding.pbBuy1.setProgress(buy_max_num - (int) Double.parseDouble(list.get((buy_index * 5) + 0).num));
                binding.pbBuy2.setProgress(buy_max_num - (int) Double.parseDouble(list.get((buy_index * 5) + 1).num));
                binding.pbBuy3.setProgress(buy_max_num - (int) Double.parseDouble(list.get((buy_index * 5) + 2).num));
                binding.pbBuy4.setProgress(buy_max_num - (int) Double.parseDouble(list.get((buy_index * 5) + 3).num));
                binding.pbBuy5.setProgress(buy_max_num - (int) Double.parseDouble(list.get((buy_index * 5) + 4).num));

                binding.buy1PriceTv.setText(list.get((buy_index * 5) + 0).price);
                binding.buy1NumTv.setText(list.get((buy_index * 5) + 0).num);
                binding.buy2PriceTv.setText(list.get((buy_index * 5) + 1).price);
                binding.buy2NumTv.setText(list.get((buy_index * 5) + 1).num);
                binding.buy3PriceTv.setText(list.get((buy_index * 5) + 2).price);
                binding.buy3NumTv.setText(list.get((buy_index * 5) + 2).num);
                binding.buy4PriceTv.setText(list.get((buy_index * 5) + 3).price);
                binding.buy4NumTv.setText(list.get((buy_index * 5) + 3).num);
                binding.buy5PriceTv.setText(list.get((buy_index * 5) + 4).price);
                binding.buy5NumTv.setText(list.get((buy_index * 5) + 4).num);
                buy_index++;
                if (buy_index == 3) {
                    buy_index = 0;
                }
            }
        }
        if (!isStop) {
            mHandler.sendEmptyMessageDelayed(1, 1000);
        }
    }

    private void reFreshSell() {
        List<FiveBuyFiveSellEntity> list = viewModel.mFiveSellEntitys.getValue();
        if (null != list && list.size() > 0) {
            if (sell_index * 5 < list.size()) {
//                Log.e("TAG",sell_index+"====sell_index=======reFreshSell===========");
                binding.pbSell1.setProgress(sell_max_num - (int) Double.parseDouble(list.get((sell_index * 5) + 0).num));
                binding.pbSell2.setProgress(sell_max_num - (int) Double.parseDouble(list.get((sell_index * 5) + 1).num));
                binding.pbSell3.setProgress(sell_max_num - (int) Double.parseDouble(list.get((sell_index * 5) + 2).num));
                binding.pbSell4.setProgress(sell_max_num - (int) Double.parseDouble(list.get((sell_index * 5) + 3).num));
                binding.pbSell5.setProgress(sell_max_num - (int) Double.parseDouble(list.get((sell_index * 5) + 4).num));

                binding.sell1PriceTv.setText(list.get((sell_index * 5) + 0).price);
                binding.sell1NumTv.setText(list.get((sell_index * 5) + 0).num);
                binding.sell2PriceTv.setText(list.get((sell_index * 5) + 1).price);
                binding.sell2NumTv.setText(list.get((sell_index * 5) + 1).num);
                binding.sell3PriceTv.setText(list.get((sell_index * 5) + 2).price);
                binding.sell3NumTv.setText(list.get((sell_index * 5) + 2).num);
                binding.sell4PriceTv.setText(list.get((sell_index * 5) + 3).price);
                binding.sell4NumTv.setText(list.get((sell_index * 5) + 3).num);
                binding.sell5PriceTv.setText(list.get((sell_index * 5) + 4).price);
                binding.sell5NumTv.setText(list.get((sell_index * 5) + 4).num);
                sell_index++;
                if (sell_index == 3) {
                    sell_index = 0;
                }
            }
        }
        if (!isStop) {
            mHandler.sendEmptyMessageDelayed(2, 1000);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isStop = false;
        mHandler.sendEmptyMessageDelayed(1, 1000);
        mHandler.sendEmptyMessageDelayed(2, 1000);
    }

    @Override
    public void onPause() {
        super.onPause();
        isStop = true;
    }

    private boolean isStop = false;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                reFreshBuy();
            } else if (msg.what == 2) {
                reFreshSell();
            }
        }
    };

    @Override
    public void initData() {
        super.initData();
        SpUtils.put(getActivity(), "otcPlanCreate", "1");
//        viewModel.apiConfigs();
//        viewModel.walletCoins();
//
//
//        viewModel.baseUser();
//        viewModel.otcPlanData();//挂单数据
//        viewModel.fiveBuy();
//        viewModel.fiveSell();
//        viewModel.otcWallet("");//钱包余额

        initRefreshLayout();

        binding.twinklingRefreshLayout.autoRefresh();
//        viewModel.login();

        binding.tvDuihuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!Utils.isLogin()) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("type", "CSC");
                startContainerActivity(ExchangePointsFragment.class.getCanonicalName(), bundle);
            }
        });

        binding.doBuyTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isBuy) {
                    isBuy = true;
                    binding.doBuyTv.setBackgroundResource(R.mipmap.buy_select_img);
                    binding.doBuyTv.setTextColor(getResources().getColor(R.color.white));
                    binding.doSellTv.setTextColor(getResources().getColor(R.color.my_color_000000));
                    binding.doSellTv.setBackgroundResource(R.mipmap.sell_img);
                    binding.tvQiugou.setText("求购");
                    binding.cankaojiageTv.setText(cankaojiage_buy);
                }
            }
        });

        binding.doSellTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isBuy) {
                    isBuy = false;
                    binding.doBuyTv.setBackgroundResource(R.mipmap.buy_unselect_img);
                    binding.doSellTv.setBackgroundResource(R.mipmap.sell_selec_img);
                    binding.doSellTv.setTextColor(getResources().getColor(R.color.white));
                    binding.doBuyTv.setTextColor(getResources().getColor(R.color.my_color_000000));
                    binding.tvQiugou.setText("转赠");
                    binding.cankaojiageTv.setText(cankaojiage_sell);
                }
            }
        });

        binding.tvQiugou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAuthentication = SpUtils.getInt(getActivity(),"authentication");
                if (mAuthentication!=1){
                    if (mAuthentication == 0){
                        ToastUtil.showToast("请先进行实名认证");
                    }else if (mAuthentication == 2){
                        ToastUtil.showToast("您提交的实名认证失败，请重新认证");
                    }else if (mAuthentication == 3){
                        ToastUtil.showToast("您提交的实名认证正在审核，请耐心等待");
                    }
                    return;
                }
                if (TextUtil.isEmpty(binding.marketPriceEt.getText().toString())) {
                    ToastUtil.showToast("请输入价格");
                    return;
                }
                if (TextUtil.isEmpty(binding.marketNumEt.getText().toString())) {
                    ToastUtil.showToast("请输入数量");
                    return;
                }
                if (Integer.parseInt(binding.marketNumEt.getText().toString()) > 1000) {
                    ToastUtil.showToast("请输入数量小于1000");
                    return;
                }
                if (!Utils.isLogin()) {
                    return;
                }
                if (!isBuy)//转赠要判断余额
                {
                    double money = 0;
                    if (mCSCWalletEntity != null) {
                        money = Double.parseDouble(mCSCWalletEntity.money);
                    }
                    double num = Double.parseDouble(binding.marketNumEt.getText().toString());
                    if (num > money) {
                        ToastUtil.showToast("可用CSC不足");
                        return;
                    }
                }
                if (isBuy) {
                    qiuGou(view, isBuy, null);
                } else {
                    viewModel.otcPayCccount();
                }
            }
        });

        viewModel.mConfigEntity.observe(this, new Observer<ConfigEntity>() {
            @Override
            public void onChanged(ConfigEntity configEntity) {
//                GlideUtils.getInstances().loadNormalImg(getContext(),binding.topImg,"/" + configEntity.top_ad_image);
                try {
                    String versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
                    if (configEntity.apk != null) {
                        if (Utils.compareVersion(configEntity.apk.version, versionName) == 1) {
                            Utils.showWarnDialog(configEntity, getActivity());
                        }
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }

                //tips_show为1  展示提示
                if (configEntity.config.tip_show.equals("1")) {
                    String verTime = SpUtils.get(getActivity(), "mainVerification");
                    if (!verTime.isEmpty()) {
                        //获取当天零点时间戳
                        long time = TimeUtil.getZeroClockTimestamp(System.currentTimeMillis());
                        //获取记录的时间 零点的时间戳
                        long recordTime = TimeUtil.getZeroClockTimestamp(Long.parseLong(verTime));
                        if (time != recordTime) {
                            //不在同一天
                            isVerification = false;
                        } else {
                            //再同一天
                            isVerification = true;
                        }
                    } else {
                        isVerification = false;
                    }
                    if (!isVerification) {
                        //提示购买
                        initTipPop(configEntity);
                    }
                }
            }
        });
        viewModel.mPlanIndexEntity.observe(this, new Observer<PlanIndexEntity>() {
            @Override
            public void onChanged(PlanIndexEntity planIndexEntity) {
                buy_max_num = planIndexEntity.buy_set.max_list_num;
                sell_max_num = planIndexEntity.sell_set.max_list_num;
                binding.pbBuy1.setMax(planIndexEntity.buy_set.max_list_num);
                binding.pbBuy2.setMax(planIndexEntity.buy_set.max_list_num);
                binding.pbBuy3.setMax(planIndexEntity.buy_set.max_list_num);
                binding.pbBuy4.setMax(planIndexEntity.buy_set.max_list_num);
                binding.pbBuy5.setMax(planIndexEntity.buy_set.max_list_num);
                binding.pbSell1.setMax(planIndexEntity.sell_set.max_list_num);
                binding.pbSell2.setMax(planIndexEntity.sell_set.max_list_num);
                binding.pbSell3.setMax(planIndexEntity.sell_set.max_list_num);
                binding.pbSell4.setMax(planIndexEntity.sell_set.max_list_num);
                binding.pbSell5.setMax(planIndexEntity.sell_set.max_list_num);
                binding.totalNumValueTv.setText(planIndexEntity.today_amount + "CSC");
                binding.todayNumValueTv.setText(planIndexEntity.today_count + "笔");

//                double max = planIndexEntity.buy_set.price * ((planIndexEntity.buy_set.max_price_ratio/100d) + 1);
//                double min = planIndexEntity.buy_set.price * ((planIndexEntity.buy_set.min_price_ratio/100d) + 1);
//                Log.e("TAG",max + "=====max================min========"+min + " CSC:"+planIndexEntity.today_amount);
//                binding.cankaojiageTv.setText(NumberUtils.keepPrecision(min,2) + "-" + NumberUtils.keepPrecision(max,2));

                cankaojiage_buy = planIndexEntity.buy_set.min_price + "-" + planIndexEntity.buy_set.max_price;
                cankaojiage_sell = planIndexEntity.sell_set.min_price + "-" + planIndexEntity.sell_set.max_price;
                if (isBuy) {
                    binding.cankaojiageTv.setText(cankaojiage_buy);
                } else {
                    binding.cankaojiageTv.setText(cankaojiage_sell);
                }
            }
        });
        mSubscription = RxBus.getDefault().toObservable(com.app.newcsc.entity.Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<com.app.newcsc.entity.Message>() {
                    @Override
                    public void accept(final com.app.newcsc.entity.Message message) throws Exception {
                        Log.e("TAG", "===============message==============" + message.getName());
                        if (message.getName().equals("start_login")) {
//                            viewModel.baseUser();
//                            viewModel.otcPlanData();//挂单数据
//                            viewModel.fiveBuy();
//                            viewModel.fiveSell();
//                            viewModel.otcWallet("");//钱包余额

                            viewModel.apiConfigs();
                        } else if (message.getName().equals("MainActivity_index_0")) {
                            if ((viewModel.mFiveBuyEntitys.getValue() == null || viewModel.mFiveBuyEntitys.getValue().size() < 1
                                    || viewModel.mFiveSellEntitys.getValue() == null || viewModel.mFiveSellEntitys.getValue().size() < 1)
                                    && Utils.isFastClick()) {
                                viewModel.apiConfigs();
                            }
                        } else if (message.getName().equals("RefreshExchange")) {
                            viewModel.otcWallet("");//钱包余额
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);

        //提取第三方AIpass 请求token
        viewModel.mGetTokenEntity.observe(this, new Observer<GetTokenEntity>() {
            @Override
            public void onChanged(GetTokenEntity getTokenEntity) {
                SpUtils.put(getActivity(), "getshoptoken", getTokenEntity.token_type + " " + getTokenEntity.access_token);
                //判断返回哪个app
//                if (SpUtils.get(getActivity(),"ai_apptag").equals("com.app.gold")){
//                    goGold();
//                }else {
                goAI(1);
//                }

            }
        });

        viewModel.mWalletEntitys.observe(this, new Observer<List<WalletEntity>>() {
            @Override
            public void onChanged(List<WalletEntity> walletEntities) {
                boolean isTop = false;
                for (int i = 0; i < walletEntities.size(); i++) {
                    WalletEntity mWalletEntity = walletEntities.get(i);
                    if (mWalletEntity.coin_name.equals("AD")) {
//                        mAdWalletEntity = mWalletEntity;
//                        binding.fountAdTv.setText(mWalletEntity.money);
//                        binding.typeTv.setText("可用"+mWalletEntity.coin_name);
//                        binding.adNum.setText(mWalletEntity.money);
//                        binding.dongjieTv.setText("冻结: "+mWalletEntity.lockups+"CSC");
                    } else if (mWalletEntity.coin_name.equals("CSC")) {
                        mCSCWalletEntity = mWalletEntity;
//                        binding.fountCscTv.setText(mWalletEntity.money);
                        break;
                    } else if (mWalletEntity.coin_name.equals("用户账户")) {
//                        mYongHuWalletEntity = mWalletEntity;
//                        binding.fountYonghuTv.setText(mWalletEntity.money);
                    } else if (mWalletEntity.coin_name.equals("发布账户")) {
//                        mFaBuWalletEntity = mWalletEntity;
//                        binding.fountFabuTv.setText(mWalletEntity.money);
                    }
//                    if(!isTop)
//                    {
//                        isTop = true;
//                        binding.typeTv.setText("可用"+mWalletEntity.coin_name);
//                        binding.adNum.setText(mWalletEntity.money);
//                        binding.dongjieTv.setText(mWalletEntity.lockups);
//                    }
                }
                if (mCSCWalletEntity != null) {
                    double cscNum = Double.valueOf(mCSCWalletEntity.money)-Double.valueOf(mCSCWalletEntity.lock_s_one);

                    binding.keyongTv.setText(NumberUtils.keepPrecision(cscNum, 4) + " CSC");
                }
            }
        });
        binding.marketPriceEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable != null && binding.marketNumEt != null && !TextUtil.isEmpty(binding.marketNumEt.getText().toString()) && !TextUtil.isEmpty(editable.toString())) {
                    if (binding.marketNumEt.getText().toString().trim().length() > 0 && editable.toString().trim().length() > 0) {
                        double price = Double.parseDouble(editable.toString().trim());
                        double num = Double.parseDouble(binding.marketNumEt.getText().toString().trim());
                        binding.jiaoyieTv.setText(NumberUtils.keepPrecision((price * num), 2) + AppApplication.priceType);//CNY
                    } else {
                        binding.jiaoyieTv.setText("0" + AppApplication.priceType);//CNY
                    }
                } else {
                    binding.jiaoyieTv.setText("0" + AppApplication.priceType);//CNY
                }
            }
        });
        binding.marketNumEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable != null && binding.marketPriceEt != null && !TextUtil.isEmpty(binding.marketPriceEt.getText().toString()) && !TextUtil.isEmpty(editable.toString())) {
                    if (binding.marketPriceEt.getText().toString().trim().length() > 0 && editable.toString().trim().length() > 0) {
                        double price = Double.parseDouble(binding.marketPriceEt.getText().toString().trim());
                        double num = Double.parseDouble(editable.toString().trim());
                        binding.jiaoyieTv.setText(NumberUtils.keepPrecision((price * num), 2) + AppApplication.priceType);//CNY
                    } else {
                        binding.jiaoyieTv.setText("0" + AppApplication.priceType);//CNY
                    }
                } else {
                    binding.jiaoyieTv.setText("0" + AppApplication.priceType);//CNY
                }
            }
        });
        viewModel.mPayAccountEntitys.observe(this, new Observer<List<PayAccountEntity>>() {
            @Override
            public void onChanged(List<PayAccountEntity> payAccountEntities) {
                if (payAccountEntities == null || payAccountEntities.size() < 1) {
                    ToastUtil.showToast("请添加收款方式");
                    return;
                }
                qiuGou(binding.tvQiugou, isBuy, payAccountEntities);
            }
        });

        viewModel.otcPlanCreateBoolean.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (anquanYanzhengPopWindow != null) {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }
            }
        });

        if (!TextUtils.isEmpty(SpUtils.get(getActivity(), "ai_apptag"))
                && !TextUtils.isEmpty(SpUtils.get(getActivity(), "ai_code"))
                && !TextUtils.isEmpty(SpUtils.get(getActivity(), "ai_name")) && isFastClick()) {
            AuthorizationDialog dialog = new AuthorizationDialog(getActivity());
            dialog.show(v -> {
                if (!TextUtils.isEmpty(SpUtils.get(getActivity(), "ai_type"))) {
                    getshoptoken();
                } else {
//                    sendData();
                }
                dialog.dismiss();
            });
            dialog.cancel(v -> {
                dialog.dismiss();
//                goCSC(0);
            });
        }
    }

    private void goAI(int i) {
        Intent intent = getActivity().getPackageManager().getLaunchIntentForPackage(SpUtils.get(getActivity(), "ai_apptag"));
//        Intent intent = new Intent("com.app.aipass.activity.MainActivity");
        if (intent != null) {
            if (i != 0) {
//                intent.putExtra("token", SpUtils.getToken());
                if (SpUtils.get(getActivity(), "ai_apptag").equals("com.zhilingshenghuo.app.zhly")) {
                    intent.putExtra("token", ShareUtil.getInstance().get(ShareUtil.ACCESS_TOKEN));
                    intent.putExtra("phone", SpUtils.get(getActivity(), "phone"));
                } else {
                    if (!TextUtils.isEmpty(SpUtils.get(getActivity(), "getshoptoken"))) {
                        intent.putExtra("token", SpUtils.get(getActivity(), "getshoptoken"));
                    }
                }
//                else
//                {
//                    intent.putExtra("token",SpUtils.get("token_type") + " " + SpUtils.get("access_token"));
//                }
            }
            SpUtils.put(getActivity(), "ai_type", "");
            SpUtils.put(getActivity(), "ai_name", "");
            SpUtils.put(getActivity(), "ai_code", "");
            SpUtils.put(getActivity(), "ai_apptag", "");
//            Log.e("TAG",i + "=======goCSC=========token========"+SpUtils.getToken());
            startActivity(intent);
        }
        getActivity().finish();
    }

    //获取
    private void getshoptoken() {
        viewModel.getToken();
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;

//        return true;
    }


    private CustomPopWindow mCustomPopWindow;
    private String type_select = "";
    private String banktype_select = "";
    private String zfbtype_select = "";
    private String wxtype_select = "";

    private void qiuGou(View view, boolean isBuy, List<PayAccountEntity> payAccountEntities) {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_market_qiugou, null);
        TextView title_tv = contentView.findViewById(R.id.title_tv);//价格
        title_tv.setText(isBuy ? "求购CSC" : "转赠CSC");
        EditText guadan_price_et = contentView.findViewById(R.id.guadan_price_et);//价格
        guadan_price_et.setEnabled(false);
        EditText guadan_num_et = contentView.findViewById(R.id.guadan_num_et);//数量
        guadan_price_et.setText(binding.marketPriceEt.getText().toString());
        guadan_num_et.setText(binding.marketNumEt.getText().toString());
        MCheckBox mcb_bank = contentView.findViewById(R.id.mcb_bank);
        MCheckBox mcb_zfb = contentView.findViewById(R.id.mcb_zfb);
        MCheckBox mcb_wx = contentView.findViewById(R.id.mcb_wx);

        LinearLayout ll_bank = contentView.findViewById(R.id.ll_bank);
        LinearLayout ll_zfb = contentView.findViewById(R.id.ll_zfb);
        LinearLayout ll_wx = contentView.findViewById(R.id.ll_wx);
        if (!isBuy && payAccountEntities != null && payAccountEntities.size() > 0) {
            ll_bank.setVisibility(View.GONE);
            ll_zfb.setVisibility(View.GONE);
            ll_wx.setVisibility(View.GONE);
            for (PayAccountEntity entity : payAccountEntities) {
                if (entity.type == 1) {
                    ll_bank.setVisibility(View.VISIBLE);
                } else if (entity.type == 2) {
                    ll_zfb.setVisibility(View.VISIBLE);
                } else if (entity.type == 3) {
                    ll_wx.setVisibility(View.VISIBLE);
                }
            }
        }

        contentView.findViewById(R.id.ll_bank).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mcb_bank.setChecked(!mcb_bank.isCheck());
                if (mcb_bank.isCheck()) {
                    banktype_select = "1,";
                } else {
                    banktype_select = "";
                }
            }
        });
        contentView.findViewById(R.id.ll_zfb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mcb_zfb.setChecked(!mcb_zfb.isCheck());
                if (mcb_zfb.isCheck()) {
                    zfbtype_select = "2,";
                } else {
                    zfbtype_select = "";
                }
            }
        });
        contentView.findViewById(R.id.ll_wx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mcb_wx.setChecked(!mcb_wx.isCheck());
                if (mcb_wx.isCheck()) {
                    wxtype_select = "3,";
                } else {
                    wxtype_select = "";
                }
            }
        });

        contentView.findViewById(R.id.tv_duihuan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtil.isEmpty(banktype_select) && TextUtil.isEmpty(zfbtype_select) && TextUtil.isEmpty(wxtype_select)) {
                    ToastUtil.showToast("请选择收款方式");
                    return;
                }
                type_select = banktype_select + zfbtype_select + wxtype_select;
                type_select = type_select.substring(0, type_select.length() - 1);
                Log.e("TAG", "===========type_select===================" + type_select);
                anquanYanzheng(binding.tvQiugou, isBuy, binding.marketPriceEt.getText().toString(), guadan_num_et.getText().toString(), type_select);

                binding.marketNumEt.setText("");
                mCustomPopWindow.dissmiss();
            }
        });

        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.3f) // 控制亮度
                .setFocusable(true)
                .setOutsideTouchable(true)
//                .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAtLocation(view, Gravity.BOTTOM, 0, 20);
//                .showAsDropDown(view,0,20);
    }

    private CustomPopWindow anquanYanzhengPopWindow;

    private void anquanYanzheng(View view, boolean isBuy, String price, String num, String pay_types) {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_anquan_yanzheng, null);
        EditText cede_et = contentView.findViewById(R.id.cede_et);
        TextView cancel_tv = contentView.findViewById(R.id.cancel_tv);
        EditText cede_yzm_et = contentView.findViewById(R.id.cede_yzm_et);
        EditText idcard_et = contentView.findViewById(R.id.idcard_et);
        RelativeLayout cede_yzm_rl = contentView.findViewById(R.id.cede_yzm_rl);
        if (isBuy) {
            cede_yzm_rl.setVisibility(View.GONE);
            idcard_et.setVisibility(View.GONE);
            cede_yzm_et.setVisibility(View.GONE);
        }
        cancel_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (anquanYanzhengPopWindow != null) {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }
            }
        });
        TextView forget_tv = contentView.findViewById(R.id.forget_tv);
        forget_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (anquanYanzhengPopWindow != null) {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }

                startContainerActivity(SafeFragment.class.getCanonicalName());
            }
        });
        TextView get_sms_code_tv = contentView.findViewById(R.id.get_sms_code_tv);
        get_sms_code_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.smsCode((TextView) view);
            }
        });
        TextView tv_queren = contentView.findViewById(R.id.tv_queren);
        tv_queren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String isBuyOtc = SpUtils.get(getActivity(), "otcPlanCreate");
                if (!isBuyOtc.equals("1")) {
                    ToastUtil.showToast("请稍后");
                    return;
                }
                if (TextUtil.isEmpty(cede_et.getText().toString())) {
                    ToastUtil.showToast("请输入密码");
                    return;
                }
                if (!isBuy) {
                    if (TextUtil.isEmpty(idcard_et.getText().toString())) {
                        ToastUtil.showToast("请输入身份证后六位");
                        return;
                    }
                    if (TextUtil.isEmpty(cede_yzm_et.getText().toString())) {
                        ToastUtil.showToast("请输入验证码");
                        return;
                    }
                }
//                if(anquanYanzhengPopWindow != null)
//                {
//                    anquanYanzhengPopWindow.dissmissNoRecovery();
//                }
                HashMap<String, Object> map = new HashMap<>();
//                String pay_types = "1";
                map.put("type", isBuy ? 1 : 2);//类型:1=购买,2=出售
                map.put("num", num);//挂单数量
                map.put("pay_types", pay_types);//支付方式: 1,2,3
                map.put("price", price);//价格
                map.put("payment_password", cede_et.getText().toString());
                if (!isBuy) {
                    map.put("idcard", idcard_et.getText().toString());//身份证尾号6位,如果type=2必填
                    map.put("code", cede_yzm_et.getText().toString());//短信码, 如果type=2必填
                }
                Log.e("TAG", "===========otcPlanCreate========type====" + isBuy + " num:" + num + " pay_types:" + pay_types
                        + " payment_password:" + cede_et.getText().toString() + " price:" + price);
                SpUtils.put(getActivity(), "otcPlanCreate", "2");
                viewModel.otcPlanCreate(getActivity(), map);

            }
        });
        contentView.findViewById(R.id.content_rl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (anquanYanzhengPopWindow != null) {
                    anquanYanzhengPopWindow.dissmissNoRecovery();
                }
            }
        });

        //创建并显示popWindow
        anquanYanzhengPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.3f) // 控制亮度
                .setFocusable(true)
                .setOutsideTouchable(true)
//                .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAtLocation(view, Gravity.BOTTOM, 0, 20);
//                .showAsDropDown(view,0,20);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSubscription != null) {
            RxSubscriptions.remove(mSubscription);
        }
        if (mCustomPopWindow != null) {
            mCustomPopWindow.dissmiss();
        }
        if (anquanYanzhengPopWindow != null) {
            anquanYanzhengPopWindow.dissmiss();
        }
    }

    private Disposable mSubscription;

    private void initRefreshLayout() {
        binding.twinklingRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.apiConfigs();
//                viewModel.walletCoins();
//
//
//                viewModel.baseUser();
//                viewModel.otcPlanData();//挂单数据
//                viewModel.fiveBuy();
//                viewModel.fiveSell();
//                viewModel.otcWallet("");//钱包余额
            }
        });
        binding.twinklingRefreshLayout.setEnableLoadMore(false);
        binding.twinklingRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }
        });
//        binding.twinklingRefreshLayout.autoRefresh();
    }

    @Override
    public void initViewObservable() {
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishRefresh();
//                viewModel.dismissDialog();
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishLoadMore();
//                viewModel.dismissDialog();
            }
        });
    }

    private boolean isVerification = false;
    private CustomPopWindow mTipPopWindow;
    private boolean isSelect = false;

    private void initTipPop(ConfigEntity configEntity) {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_tips_main_fragment, null);
        LinearLayout llSelect = contentView.findViewById(R.id.llSelect);
        MCheckBox mCheckBox = contentView.findViewById(R.id.mcb_select);
        TextView tvTitle = contentView.findViewById(R.id.tvTitle);
        TextView tvContent = contentView.findViewById(R.id.tvContent);
        TextView tvSure = contentView.findViewById(R.id.tvSure);

        tvTitle.setText(configEntity.config.tip_title);
        tvContent.setText(configEntity.config.tip_content);

        llSelect.setOnClickListener(v -> {
            if (isSelect){
                mCheckBox.setChecked(false);
                isSelect = false;
            }else {
                mCheckBox.setChecked(true);
                isSelect = true;
            }
        });

        tvSure.setOnClickListener(v -> {
            if (isSelect){
                //保存时间戳
                long time = System.currentTimeMillis();
                SpUtils.put(getActivity(),"mainVerification", String.valueOf(time));
            }
            mTipPopWindow.dissmissNoRecovery();
        });

        //创建并显示popWindow
        mTipPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.3f) // 控制亮度
                .setFocusable(true)
                .setOutsideTouchable(true)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAtLocation(this.getView(),Gravity.CENTER, 0, 20);
    }
}
